package com.ydlclass.serialize.Impl;

import com.ydlclass.exceptions.SerializerException;
import com.ydlclass.serialize.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * JDK类型的序列化与反序列化的方式
 * @Author duWenJian
 * @Date 2023/11/3 10:49
 * @Version 1.0
 */
@Slf4j
public class JdkSerializer implements Serializer {
    @Override
    public byte[] serialize(Object object) {
        if (object == null){
            return null;
        }
        // 将流的定义写在try()中,不需要再手动关闭
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream outputStream = new ObjectOutputStream(baos)){
            outputStream.writeObject(object);
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("序列化{}时发生异常",object);
            throw new SerializerException("序列化失败");
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if (bytes == null || clazz == null){
            return null;
        }
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
             ObjectInputStream inputStream = new ObjectInputStream(bais)){
            return (T) inputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            log.error("反序列化{}时发生异常",clazz);
            throw new SerializerException("反序列化失败");
        }
    }
}
